// 注册生长调控页面处理程序
pageManager.registerPage('growth', {
    // 保存页面状态
    currentCrop: 'wheat',  // 默认为小麦
    chartInstance: null,
    
    // 作物生长参数配置
    cropConfigs: {
        rice: {
            name: '水稻',
            stages: ['秧苗期', '分蘖期', '抽穗期', '灌浆期', '成熟期'],
            growthDays: 120,
            optimalParams: {
                temperature: { min: 22, max: 28, unit: '°C' },
                humidity: { min: 60, max: 70, unit: '%' },
                light: { min: 50000, max: 80000, unit: ' lux' },
                co2: { min: 400, max: 800, unit: ' ppm' }
            },
            heightRange: { min: 50, max: 120, unit: ' cm' },
            leafIndexRange: { min: 3.5, max: 6.0 },
            stageAdvice: {
                '秧苗期': {
                    urgent: '保持秧田水温，防止烂秧',
                    notice: '控制水层深度3-5cm',
                    longTerm: '培育壮秧，为后期打好基础'
                },
                '分蘖期': {
                    urgent: '保持适宜水温和水层深度',
                    notice: '适时追肥，促进分蘖',
                    longTerm: '控制氮肥用量，防止徒长'
                },
                '抽穗期': {
                    urgent: '注意防止倒伏，控制水层深度',
                    notice: '防治病虫害，保证授粉',
                    longTerm: '准备收获期管理工作'
                },
                '灌浆期': {
                    urgent: '保持田间湿润，防止断水',
                    notice: '防治稻瘟病，保证灌浆',
                    longTerm: '准备收割工具'
                },
                '成熟期': {
                    urgent: '注意天气变化，适时收割',
                    notice: '控制晒场环境，防止发芽',
                    longTerm: '做好储存准备工作'
                }
            }
        },
        wheat: {
            name: '小麦',
            stages: ['出苗期', '分蘖期', '拔节期', '抽穗期', '成熟期'],
            growthDays: 240,
            optimalParams: {
                temperature: { min: 18, max: 24, unit: '°C' },
                humidity: { min: 55, max: 65, unit: '%' },
                light: { min: 45000, max: 75000, unit: ' lux' },
                co2: { min: 380, max: 700, unit: ' ppm' }
            },
            heightRange: { min: 40, max: 100, unit: ' cm' },
            leafIndexRange: { min: 3.0, max: 5.5 },
            stageAdvice: {
                '出苗期': {
                    urgent: '保持土壤墒情，促进均匀出苗',
                    notice: '注意防治地下害虫',
                    longTerm: '适时补苗，确保苗齐'
                },
                '分蘖期': {
                    urgent: '控制温度和水分，促进分蘖',
                    notice: '适时浇水追肥',
                    longTerm: '为拔节期做准备'
                },
                '拔节期': {
                    urgent: '注意防寒防冻',
                    notice: '控制氮肥用量',
                    longTerm: '准备抽穗期管理'
                },
                '抽穗期': {
                    urgent: '防止干热风危害',
                    notice: '注意防治赤霉病',
                    longTerm: '准备收获期管理'
                },
                '成熟期': {
                    urgent: '注意天气变化，适时收获',
                    notice: '控制收获水分',
                    longTerm: '做好储存准备'
                }
            }
        },
        corn: {
            name: '玉米',
            stages: ['苗期', '拔节期', '抽雄期', '灌浆期', '成熟期'],
            growthDays: 100,
            optimalParams: {
                temperature: { min: 20, max: 30, unit: '°C' },
                humidity: { min: 50, max: 65, unit: '%' },
                light: { min: 60000, max: 90000, unit: ' lux' },
                co2: { min: 450, max: 850, unit: ' ppm' }
            },
            heightRange: { min: 150, max: 250, unit: ' cm' },
            leafIndexRange: { min: 4.0, max: 7.0 }
        },
        soybean: {
            name: '大豆',
            stages: ['出苗期', '分枝期', '开花期', '结荚期', '成熟期'],
            growthDays: 90,
            optimalParams: {
                temperature: { min: 20, max: 25, unit: '°C' },
                humidity: { min: 55, max: 70, unit: '%' },
                light: { min: 40000, max: 70000, unit: ' lux' },
                co2: { min: 350, max: 650, unit: ' ppm' }
            },
            heightRange: { min: 30, max: 90, unit: ' cm' },
            leafIndexRange: { min: 2.5, max: 5.0 }
        }
    },

    init() {
        this.initCropSelect();
        this.initGrowthChart();
        this.initControlActions();
        this.updateAllData();  // 初始化时更新所有数据
    },

    cleanup() {
        if (this.chartInstance) {
            this.chartInstance.dispose();
        }
    },

    // 初始化作物选择
    initCropSelect() {
        const cropSelect = document.getElementById('cropType');
        if (!cropSelect) {
            console.error('找不到作物选择下拉框');
            return;
        }
        console.log('当前选中的作物:', cropSelect.value);
        
        // 设置默认选中值
        cropSelect.value = this.currentCrop;
        cropSelect.addEventListener('change', (e) => {
            console.log('作物切换为:', e.target.value);
            this.currentCrop = e.target.value;
            this.updateAllData();
        });
    },

    // 初始化生长趋势图表
    initGrowthChart() {
        this.chartInstance = echarts.init(document.getElementById('growthChart'));
        
        // 监听指标切换
        document.getElementById('growthMetric').addEventListener('change', () => {
            this.updateGrowthChart();
        });

        this.updateGrowthChart();
    },

    // 更新生长趋势图表
    updateGrowthChart() {
        const metric = document.getElementById('growthMetric').value;
        const data = this.generateGrowthData(metric);
        
        const option = {
            title: {
                text: this.getMetricTitle(metric),
                left: 'center'
            },
            tooltip: {
                trigger: 'axis'
            },
            xAxis: {
                type: 'category',
                data: data.map(item => item.date)
            },
            yAxis: {
                type: 'value',
                name: this.getMetricUnit(metric)
            },
            series: [{
                data: data.map(item => item.value),
                type: 'line',
                smooth: true,
                areaStyle: {
                    opacity: 0.1
                }
            }]
        };

        this.chartInstance.setOption(option);
    },

    // 生成模拟生长数据
    generateGrowthData(metric) {
        const config = this.cropConfigs[this.currentCrop];
        const data = [];
        const now = new Date();
        
        // 生成最近30天的数据
        for (let i = 30; i >= 0; i--) {
            const date = new Date(now);
            date.setDate(date.getDate() - i);
            
            let value;
            switch (metric) {
                case 'height':
                    // 株高数据
                    const heightRange = config.heightRange;
                    value = heightRange.min + (heightRange.max - heightRange.min) * ((30 - i) / 30);
                    value = Math.floor(value * (0.9 + Math.random() * 0.2)); // 添加随机波动
                    break;
                case 'leaf':
                    // 叶面积指数数据
                    const leafRange = config.leafIndexRange;
                    value = leafRange.min + (leafRange.max - leafRange.min) * ((30 - i) / 30);
                    value = parseFloat((value * (0.95 + Math.random() * 0.1)).toFixed(1));
                    break;
                case 'biomass':
                    // 生物量数据 - 使用S形增长曲线
                    const progress = (30 - i) / 30;
                    value = 1000 / (1 + Math.exp(-10 * (progress - 0.5)));
                    value = Math.floor(value * (0.9 + Math.random() * 0.2));
                    break;
            }
            
            data.push({
                date: date.toLocaleDateString(),
                value: value
            });
        }
        
        return data;
    },

    // 获取指标标题
    getMetricTitle(metric) {
        const titles = {
            height: `${this.cropConfigs[this.currentCrop].name}株高变化趋势`,
            leaf: '叶面积指数变化趋势',
            biomass: '生物量积累趋势'
        };
        return titles[metric];
    },

    // 获取指标单位
    getMetricUnit(metric) {
        const units = {
            height: 'cm',
            leaf: 'LAI',
            biomass: 'g/m²'
        };
        return units[metric];
    },

    // 初始化控制按钮事件
    initControlActions() {
        document.querySelectorAll('.btn-control').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const action = e.target.textContent;
                const card = e.target.closest('.control-card');
                const parameter = card.querySelector('h4').textContent;
                
                // 这里添加实际的控制逻辑
                console.log(`${action} ${parameter}`);
                
                // 模拟更新状态
                this.updateControlStatus(card);
            });
        });
    },

    // 更新控制状态
    updateControlStatus(card) {
        const status = card.querySelector('.status');
        const currentValue = card.querySelector('.current-value');
        
        // 模拟状态更新
        setTimeout(() => {
            const statuses = ['optimal', 'warning', 'normal', 'low'];
            const randomStatus = statuses[Math.floor(Math.random() * statuses.length)];
            
            status.className = `status ${randomStatus}`;
            currentValue.textContent = this.generateRandomValue(card);
        }, 500);
    },

    // 生成随机值
    generateRandomValue(card) {
        const parameter = card.querySelector('h4').textContent;
        switch (parameter) {
            case '温度调控':
                return `${(20 + Math.random() * 10).toFixed(1)}°C`;
            case '湿度调控':
                return `${Math.floor(50 + Math.random() * 30)}%`;
            case '光照调控':
                return `${Math.floor(50000 + Math.random() * 30000)} lux`;
            case 'CO₂浓度':
                return `${Math.floor(350 + Math.random() * 450)} ppm`;
            default:
                return '0';
        }
    },

    // 更新所有数据
    updateAllData() {
        this.updateGrowthData();
        this.updateControlRanges();
        this.updateGrowthChart();
        this.updateAdvice();
    },

    // 更新生长数据
    updateGrowthData() {
        console.log('更新生长数据，当前作物:', this.currentCrop);
        const config = this.cropConfigs[this.currentCrop];
        if (!config) {
            console.error('找不到作物配置:', this.currentCrop);
            return;
        }
        
        // 计算生长进度
        const currentStage = Math.floor(Math.random() * config.stages.length);
        const progress = ((currentStage + Math.random()) / config.stages.length) * 100;
        
        // 更新生长阶段显示
        const stageBar = document.querySelector('.stage-bar');
        stageBar.style.width = `${progress}%`;
        stageBar.querySelector('span').textContent = config.stages[currentStage];

        // 更新生长天数和预计收获日期
        const passedDays = Math.floor((progress / 100) * config.growthDays);
        document.getElementById('growthDays').textContent = passedDays;

        const harvest = new Date();
        harvest.setDate(harvest.getDate() + (config.growthDays - passedDays));
        document.getElementById('harvestDate').textContent = harvest.toLocaleDateString();

        // 更新生长指标 - 根据作物特性和生长进度计算
        const heightProgress = Math.min(progress / 100, 1);
        const height = Math.floor(
            config.heightRange.min + 
            (config.heightRange.max - config.heightRange.min) * heightProgress
        );
        document.getElementById('plantHeight').textContent = `${height}${config.heightRange.unit}`;

        const leafIndex = (
            config.leafIndexRange.min + 
            (config.leafIndexRange.max - config.leafIndexRange.min) * heightProgress
        ).toFixed(1);
        document.getElementById('leafIndex').textContent = leafIndex;

        // 更新茎秆强度
        let strength;
        if (progress > 80) {
            strength = '优秀';
        } else if (progress > 50) {
            strength = '良好';
        } else {
            strength = '中等';
        }
        document.getElementById('stemStrength').textContent = strength;

        // 更新图表
        this.updateGrowthChart();
    },

    // 更新控制范围
    updateControlRanges() {
        const config = this.cropConfigs[this.currentCrop];
        const params = config.optimalParams;

        // 更新温度控制卡片
        this.updateControlCard('温度调控', params.temperature);
        this.updateControlCard('湿度调控', params.humidity);
        this.updateControlCard('光照调控', params.light);
        this.updateControlCard('CO₂浓度', params.co2);
    },

    // 更新单个控制卡片
    updateControlCard(title, param) {
        // 修改选择器以提高兼容性
        const cards = document.querySelectorAll('.card');
        const card = Array.from(cards).find(card => 
            card.querySelector('.control-header h4').textContent === title
        );
        if (!card) return;

        const range = card.querySelector('.optimal-range');
        range.textContent = `适宜范围：${param.min}-${param.max}${param.unit}`;

        // 生成当前值并确保在范围内
        let current = param.min + Math.random() * (param.max - param.min);
        current = Math.min(Math.max(current, param.min * 0.9), param.max * 1.1);  // 允许略微超出范围
        const currentValue = card.querySelector('.current-value');
        currentValue.textContent = `${current.toFixed(1)}${param.unit}`;

        // 更新状态
        const status = card.querySelector('.status');
        if (current < param.min) {
            status.className = 'status low';
            status.textContent = '偏低';
        } else if (current > param.max) {
            status.className = 'status warning';
            status.textContent = '偏高';
        } else {
            status.className = 'status optimal';
            status.textContent = '最适';
        }
    },

    // 更新建议
    updateAdvice() {
        const config = this.cropConfigs[this.currentCrop];
        const adviceContainer = document.querySelector('.farming-advice .advice-container');
        const currentStage = document.querySelector('.stage-bar span').textContent;

        // 根据作物和生长阶段生成具体建议
        const stageIndex = config.stages.indexOf(currentStage);
        const stageSpecificAdvice = this.getStageSpecificAdvice(config, stageIndex);

        // 生成建议内容
        const advices = [
            {
                icon: '⚠️',
                title: '优先处理',
                content: stageSpecificAdvice.urgent
            },
            {
                icon: '📝',
                title: '注意事项',
                content: stageSpecificAdvice.notice
            },
            {
                icon: '💡',
                title: '长期建议',
                content: stageSpecificAdvice.longTerm
            }
        ];

        // 更新建议DOM
        adviceContainer.innerHTML = advices.map(advice => `
            <div class="advice-item">
                <span class="advice-icon">${advice.icon}</span>
                <div class="advice-content">
                    <h4>${advice.title}</h4>
                    <p>${advice.content}</p>
                </div>
            </div>
        `).join('');
    },

    // 获取特定生长阶段的建议
    getStageSpecificAdvice(config, stageIndex) {
        const stage = config.stages[stageIndex];
        const stageAdvice = config.stageAdvice[stage] || {
            urgent: `${config.name}${stage}期间，注意控制温湿度在适宜范围内`,
            notice: `当前生长阶段需要保持${config.optimalParams.light.min/1000}k-${config.optimalParams.light.max/1000}k lux的光照强度`,
            longTerm: `持续监测茎秆强度，确保${config.name}健康生长`
        };

        return {
            urgent: stageAdvice.urgent,
            notice: stageAdvice.notice,
            longTerm: stageAdvice.longTerm
        };
    }
});

// 环境参数控制模块
const environmentControls = {
    temperature: {
        icon: 'fa-temperature-high',
        unit: '°C',
        current: 22,
        min: 10,
        max: 35,
        step: 0.5,
        optimal: {
            wheat: { min: 15, max: 22 },
            corn: { min: 20, max: 28 },
            rice: { min: 22, max: 30 }
        }
    },
    humidity: {
        icon: 'fa-droplet',
        unit: '%',
        current: 65,
        min: 30,
        max: 90,
        step: 1,
        optimal: {
            wheat: { min: 60, max: 75 },
            corn: { min: 65, max: 80 },
            rice: { min: 75, max: 85 }
        }
    },
    light: {
        icon: 'fa-sun',
        unit: 'klux',
        current: 60,
        min: 20,
        max: 100,
        step: 5,
        optimal: {
            wheat: { min: 50, max: 80 },
            corn: { min: 60, max: 90 },
            rice: { min: 55, max: 85 }
        }
    },
    soil: {
        icon: 'fa-water',
        unit: '%',
        current: 70,
        min: 40,
        max: 95,
        step: 1,
        optimal: {
            wheat: { min: 60, max: 75 },
            corn: { min: 65, max: 80 },
            rice: { min: 80, max: 90 }
        }
    }
};

// 渲染环境参数控制面板
function renderEnvironmentControls() {
    const container = document.createElement('div');
    container.className = 'environment-controls';
    container.innerHTML = `
        <h3>环境参数调控</h3>
        <div class="control-grid">
            ${Object.entries(environmentControls).map(([key, param]) => `
                <div class="param-control" data-param="${key}">
                    <div class="param-header">
                        <div class="param-title">
                            <i class="fas ${param.icon}"></i>
                            <span>${getParamName(key)}</span>
                        </div>
                        <div class="param-status ${getParamStatus(key, param.current)}">
                            ${getStatusText(key, param.current)}
                        </div>
                    </div>
                    <div class="param-value">
                        ${param.current}${param.unit}
                    </div>
                    <div class="param-range">
                        <span>${param.min}${param.unit}</span>
                        <span>${param.max}${param.unit}</span>
                    </div>
                    <input type="range" class="param-slider"
                           min="${param.min}" max="${param.max}" 
                           step="${param.step}" value="${param.current}"
                           data-param="${key}">
                    <div class="control-actions">
                        <button class="btn-control decrease">
                            <i class="fas fa-minus"></i>
                            <span>降低</span>
                        </button>
                        <button class="btn-control increase">
                            <i class="fas fa-plus"></i>
                            <span>提高</span>
                        </button>
                    </div>
                    <div class="auto-control">
                        <label>自动控制</label>
                        <label class="switch-button">
                            <input type="checkbox" checked>
                            <span class="switch-slider"></span>
                        </label>
                    </div>
                </div>
            `).join('')}
        </div>
    `;

    // 添加事件监听
    container.querySelectorAll('.param-slider').forEach(slider => {
        slider.addEventListener('input', handleSliderChange);
    });

    container.querySelectorAll('.btn-control').forEach(btn => {
        btn.addEventListener('click', handleControlButton);
    });

    // 替换或添加到页面
    const existingControls = document.querySelector('.environment-controls');
    if (existingControls) {
        existingControls.replaceWith(container);
    } else {
        document.querySelector('.growth-container').appendChild(container);
    }
}

// 处理滑块变化
function handleSliderChange(e) {
    const param = e.target.dataset.param;
    const value = parseFloat(e.target.value);
    updateParamValue(param, value);
}

// 处理控制按钮点击
function handleControlButton(e) {
    const param = e.target.closest('.param-control').dataset.param;
    const isIncrease = e.target.closest('.btn-control').classList.contains('increase');
    const control = environmentControls[param];
    const step = control.step;
    
    let newValue = control.current + (isIncrease ? step : -step);
    newValue = Math.min(Math.max(newValue, control.min), control.max);
    
    updateParamValue(param, newValue);
}

// 更新参数值
function updateParamValue(param, value) {
    const control = environmentControls[param];
    control.current = value;
    
    const paramControl = document.querySelector(`.param-control[data-param="${param}"]`);
    paramControl.querySelector('.param-value').textContent = `${value}${control.unit}`;
    paramControl.querySelector('.param-slider').value = value;
    
    const status = getParamStatus(param, value);
    const statusElement = paramControl.querySelector('.param-status');
    statusElement.className = `param-status ${status}`;
    statusElement.textContent = getStatusText(param, value);
}

// 获取参数状态
function getParamStatus(param, value) {
    const optimal = environmentControls[param].optimal[currentCrop];
    if (value >= optimal.min && value <= optimal.max) return 'optimal';
    if (value < optimal.min - 5 || value > optimal.max + 5) return 'critical';
    return 'warning';
}

// 获取状态文本
function getStatusText(param, value) {
    const status = getParamStatus(param, value);
    return {
        optimal: '适宜',
        warning: '注意',
        critical: '警告'
    }[status];
}

// 获取参数名称
function getParamName(param) {
    return {
        temperature: '温度',
        humidity: '湿度',
        light: '光照',
        soil: '土壤湿度'
    }[param];
}

// 在页面加载和作物切换时调用
document.addEventListener('DOMContentLoaded', () => {
    // ... 其他初始化代码 ...
    renderEnvironmentControls();
}); 